package iut.LocateWind.fr;

import java.net.URL;
import java.util.Timer;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class DataCollectorService extends Service{
	
	public static final String CONTENUDEMESSAGE = "data";
	private Timer chrono = null;
	private CollectorTimerTask ctt = null;
	private int lastSizeCheked = 0;
	private WindHandler myXMLHandler = null;
	private XMLReader xr = null;
	private URL sourceUrl = null;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void onStart(Intent intent , int startId ) {
		   chrono.scheduleAtFixedRate(ctt,0,(long)10000);
	}
	
	public void onCreate() {
		try{
			/** R�cup�ration de l'XML **/
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			xr = sp.getXMLReader();
			sourceUrl = new URL("http://eguerra.homelinux.com/locateWind/script/php/recupInfos.php");
			myXMLHandler = new WindHandler();			
		} catch(Exception e){
			System.out.println("XML Parsing error : "+e);
		}
		chrono = new Timer ( "chrono_maj_map" ) ;
		ctt = new CollectorTimerTask(this);
	}
	
	public void lance_thread_map_maj(){
		Thread updateThread = new Thread(null,recupRunnable);
		updateThread.start();
	}
	
	private Runnable recupRunnable = new Runnable(){
		public void run(){
			map_maj();	
		}
	};

	public void map_maj(){
		try{
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));
			if(lastSizeCheked == 0 || WindHandler.getWindMap().size() > lastSizeCheked){
				if(WindHandler.getWindMap().size() > 0){
					lastSizeCheked = WindHandler.getWindMap().size();
					Intent intent = new Intent("new data");
					this.sendBroadcast(intent) ;
				}
			}
		} catch(Exception e){
			System.out.println("XML Parsing error : "+e);
		}
		/* envoyer un message pour faire la maj de la vue si il y à du nouveau */
		
	}
}
